/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SuppliersBeans;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import org.hibernate.criterion.Restrictions;
import org.orm.PersistentException;
import smartgrid.Contract;
import smartgrid.DataLine;
import smartgrid.TariffCriteria;
import smartgrid.exceptions.InvalidContractNifException;
import smartgrid.exceptions.InvalidContractNumberException;

/**
 *
 * @author claudio
 */
@Stateless
public class ENDESAbean implements ENDESAbeanLocal {

    Integer supplierID = 2;

    @Override
    public Contract getContract(String number, String nif) throws InvalidContractNumberException, InvalidContractNifException {

        Random rand = new Random();
        rand.setSeed(System.nanoTime());
        Contract c = new Contract();

        /* Simular nao existencia de contrato ou nif falhado */
        int falha = rand.nextInt(10);
        if (falha == 1) {
            throw new InvalidContractNumberException();
        } else if (falha == 2) {
            throw new InvalidContractNifException();
        }

        /* ************ Insere contrato na BD ***************** */

        /* Gera uma Tarifa */

        try {
            TariffCriteria tarifCrit;
            tarifCrit = new TariffCriteria();
            tarifCrit.add(Restrictions.eq("Supplier_Tariffs_role.id", supplierID));
            tarifCrit.add(Restrictions.sqlRestriction("1=1 ORDER BY RANDOM() LIMIT 1"));
            smartgrid.Tariff tariff = smartgrid.Tariff.loadTariffByCriteria(tarifCrit);

            /* Gera um cliente */
            String clientName = Generator.generateName();
            String clientAddress = Generator.generateAddress();


            /* Cria novo contrato */
            c.setClientName(clientName);
            c.setMorada(clientAddress);
            c.setClientNif(nif);
            c.setNumber(number);
            c.setSupplier_role(smartgrid.Supplier.getSupplierByORMID(supplierID));
            c.setTariff_CurrentTarif_role(tariff);

        } catch (PersistentException ex) {
            Logger.getLogger(ENDESAbean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return c;
    }

// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
    @Override
    public DataLine[] getHistory(Contract contract) {
        return null;
    }
}
